package com.xu.cloud.common.util;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * Validation参数校验工具类
 *
 * @author xuguan
 * @since 2024/8/30
 */
public class ValidationUtil {
    public static final javax.validation.Validator VALIDATOR = javax.validation.Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 校验数据(分组)
     *
     * @param t      校验对象
     * @param groups 分组
     * @param <T>    对象类型
     * @throws ConstraintViolationException 校验失败抛出
     */
    public static <T> void validate(T t, Class<?>... groups) throws ConstraintViolationException {
        final Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(t, groups);
        throw new ConstraintViolationException(constraintViolations);

    }

    /**
     * 校验数据中的字段
     *
     * @param t            校验对象
     * @param propertyName 校验字段
     * @param groups       分组
     * @param <T>          对象类型
     * @throws ConstraintViolationException 校验失败抛出
     */
    public static <T> void validate(T t, String propertyName, Class<?>... groups) throws ConstraintViolationException {
        final Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validateProperty(t, propertyName, groups);
        throw new ConstraintViolationException(constraintViolations);
    }
}